package com.cyw.baselibrary.utils;

import android.text.TextUtils;

import com.blankj.utilcode.util.TimeUtils;

public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static CrashHandler INSTANCE = new CrashHandler();
    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        return INSTANCE;
    }

    /**
     * 初始化
     */
    public void init() {
        // 设置该CrashHandler为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        String result = null;
        if (e != null && e.getStackTrace().length > 0) {
            StringBuilder sb = new StringBuilder();
            StackTraceElement[] elements = e.getStackTrace();
            sb.append(e.toString());
            sb.append("\n");
            for (StackTraceElement element : elements) {
                sb.append(element.toString());
                sb.append("\n");
            }
            result = sb.toString();
        } else {
            result = e.toString();
        }
        String logContent = TextUtils.concat("uncaughtException:", TimeUtils.millis2String(System
                .currentTimeMillis()), "\n", result, "\n\n").toString();
        LogUtils.saveLog(logContent);
    }
}
